﻿using AutoMapper;
using MediatR;
using Warehouse.API.Applcation.Command.OutBoundCommand;
using Warehouse.Domain;
using Warehouse.Infrstructre;
using Warehouse.Infrstructre.Interface;
namespace Warehouse.API.Applcation.CommandHandlers.OutShipCommandHandlers
{
    /// <summary>
    /// 更新出库单
    /// </summary>
    public class UptOutShipCommandHandlers:IRequestHandler<UptOutShipCommand,int>
    {
        private readonly IOutShipRepository _outship;

        private  readonly IOutProductRepository _outProductRepository;

        private EFCoreDBcontext _dbContext;
        private IMapper _mapper;

        public UptOutShipCommandHandlers(IOutShipRepository _outship, IOutProductRepository outProductRepository, IMapper mapper, EFCoreDBcontext dbContext)
        {
           this. _outship = _outship;
            _outProductRepository = outProductRepository;
            _mapper = mapper;
            _dbContext = dbContext;
        }

        public async Task<int> Handle(UptOutShipCommand request, CancellationToken cancellationToken)
        {
            using (var tran = _dbContext.Database.BeginTransaction())
            {
                try
                {
                    //修改出库表
                    var outship = _mapper.Map<OutShip>(request.UptDto);
                   await _outship.UpdateAsync(outship);
                    //删除原有的出库产品
                    var del = (await _outProductRepository.GetAllAsyns()).Where(x => x.OutShipId == outship.OutShipId);
                    foreach (var item in del)
                    {
                         item.IsDel = true;
                        await _outProductRepository.UpdateAsync(item);
                    }

                    foreach (var item in request.UptDto.OutProducts)
                    {
                        OutProduct outProduct = new OutProduct()
                        {
                            OutProuductId = item.OutProuductId,
                            OutShipId = outship.OutShipId,
                            ProductsID = item.ProductsID,
                            Batch = item.Batch,
                            OutPrice = item.OutPrice,
                            OutProuductNum = item.OutProuductNum,
                            Binlocation = item.Binlocation,
                            user_id = item.user_id,
                            office_id = item.office_id,
                            AddName = item.AddName,
                            AddTime = item.AddTime,

                            
                        };
                        await _outProductRepository.AddAsync(outProduct);
                    }

                    tran.Commit();
                    return 1;
                }
                catch (Exception ex)
                {
                    tran.Rollback();
                    throw;
                }
            }
        }
    }
}
